<?php

namespace App\Console\Commands\System\Project;

use App\Models\System\Project\SystemProjectModel;
use Illuminate\Console\Command;

class ProjectGenerateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:projectGenerate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '系统：生成项目记录';

    public int $initProjectCode = 100;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        $enName = $this->getEnName();
        $cnName = $this->getCnName();

        $lastProject = SystemProjectModel::query()->orderByDesc("id")->first();
        if (empty($lastProject)) {
            $projectCode = $this->initProjectCode;
        } else {
            $projectCode = $lastProject->projectCode + 1;
        }

        SystemProjectModel::query()->insertGetId([
            "cnName"      => $cnName,
            "enName"      => $enName,
            "projectCode" => $projectCode,
            "createdAt"   => time()
        ]);

        $this->info("添加项目 {$cnName} 成功!");
        return parent::SUCCESS;
    }

    /**
     * @return mixed
     */
    public function getCnName()
    {
        if (empty($cnName = $this->ask('请输入项目中文名称'))) {
            $this->error("项目中文名称不能为空");
            return $this->getCnName();
        }
        return $cnName;
    }

    /**
     * @return string
     */
    public function getEnName(): string
    {
        if (empty($enName = $this->ask('请输入项目英文名称'))) {
            $this->error("项目英文名称不能为空");
            return $this->getEnName();
        }

        if (!preg_match("/^[a-z|A-Z][a-zA-Z_].*[a-z|A-Z]$/", $enName)) {
            $this->error("项目英文名称格式不正确（1、子母开头 2、仅包含英文字母和下划线 3、子母结尾）");
            return $this->getEnName();
        }

        if (SystemProjectModel::query()->where("enName", $enName)->exists()) {
            $this->error("项目英文名称已存在");
            return $this->getEnName();
        }

        return strtoupper($enName);
    }
}
